import {
  AfterContentInit,
  Component,
  ContentChildren,
  EventEmitter,
  Input,
  OnInit,
  Output,
  QueryList,
  SimpleChanges
} from '@angular/core';
import { NzInputDirective, NzSelectComponent, NzTreeSelectComponent } from "ng-zorro-antd";
import { LocalStorage } from "../../../utils/localstorage";

@Component({
  selector: 'meta-search',
  templateUrl: './meta-search.component.html',
  styleUrls: [ './meta-search.component.styl' ]
})
export class MetaSearchComponent implements OnInit, AfterContentInit {
  constructor() {
  }

  ngOnInit() {

  }

  ngOnChanges(changes: SimpleChanges) {
    let btns = [];
    this.btnGroup.forEach((itm) => {
      if (itm.id) {
        if (LocalStorage.isButton(itm.id)) {
          btns.push(itm);
        }
      } else {
        btns.push(itm);
      }
    });
    this.btnGroup = btns;
  }

  @ContentChildren(NzSelectComponent, { descendants: true }) selectList: QueryList<NzSelectComponent>;
  @ContentChildren(NzTreeSelectComponent, { descendants: true }) treeList: QueryList<NzTreeSelectComponent>;
  @ContentChildren(NzInputDirective, { descendants: true }) inputList: QueryList<NzInputDirective>;

  ngAfterContentInit() {
    // 组件大小全部设为小
    this.selectList.forEach(item => {
      item.nzSize = 'small';
    });
    this.treeList.forEach(item => {
      item.nzSize = 'small';
    });
    this.inputList.forEach(item => {
      item.nzSize = 'small';
    });
  }

  @Input() btnGroup = []; // 搜索之外的操作按钮
  @Input() enterSearch: boolean = true; // 回车自动搜索，默认打开
  @Input() displaySearch: Boolean = true; // 是否显示搜索状态条，默认显示，false=不显示
  @Input() operateButtonSize: string = 'small'; // 操作区域按钮大小。不指定则默认为small,可以指定为large|small|default
  @Output() btnClick = new EventEmitter<object>(); // 按钮点击
  @Output() search = new EventEmitter<object>(); // 按钮点击


  onEnterSearch(): void {
    if (this.enterSearch == true) {
      this.onSearch();
    }
  }

  /**
   * 查询
   */
  onSearch(): void {
    this.search.emit();
  }

  /**
   * 按钮点击
   * @param btnId 按钮ID
   */
  onBtnClick(btn): void {
    if (btn.click) {
      btn.click();
    } else {
      this.btnClick.emit({ 'btnId': btn.id });
    }
  }


  /**
   * 设置按钮载入状态
   * @param btnId 按钮ID
   * @param loading 载入状态
   */
  setBtnLoading(btnId, loading) {
    this.btnGroup.forEach(btn => {
      if (btn.id == btnId) {
        btn.loading = loading;
        return;
      }
    });
  }

}
